package com.shadowtorcher.dragonstreasure.filelogic;

import com.shadowtorcher.dragonstreasure.until.Until;
import com.shadowtorcher.dragonstreasure.url.DeleteURL;
import com.shadowtorcher.dragonstreasure.url.DownloadURL;

import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.DatatypeConverter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
import java.util.Date;

public class StaticFileLogic {
    public static boolean checkFileURL(DownloadURL url) {
        String checkCode = getCheckCode(url.getUUID(), url.getUsername(), url.getTime());
        if (!checkCode.equals(url.getCheckCode())) {
            return false;
        }

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(Until.decryptDate(url.getTime()));
        calendar.add(Calendar.HOUR_OF_DAY, 3); // 有效期 3 小时
        return !calendar.getTime().after(new Date());
    }

    public static boolean checkDeleteURL(DeleteURL url, HttpServletRequest httpServletRequest) {
        String UA = httpServletRequest.getHeader("User-Agent");
        return UA.contains("dragons-treasure-client");
    }

    private static String getCheckCode(String ID, String UserName, String Date) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            String checkURL = ID + UserName + Date + "Magic String";
            messageDigest.update(checkURL.getBytes());
            String md5String = DatatypeConverter.printHexBinary(messageDigest.digest()).toUpperCase();
            return md5String.substring(0, 4);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return "";
        }
    }
}
